#!/usr/bin/env python3
"""
AI日记路由 - 后端

功能：
1. 日记条目的CRUD操作
2. AI生成每日总结
3. 心情和天气记录
"""

from flask import Blueprint, request, jsonify
from flask_jwt_extended import jwt_required, get_jwt_identity
from models import db, DiaryEntry, DiarySummary
from datetime import datetime, date
import requests
import os

bp = Blueprint('ai_dairy', __name__)


# ==================== GET - 获取日记条目列表 ====================
@bp.route('/entries', methods=['GET'])
@jwt_required()
def get_diary_entries():
    """获取用户的日记条目列表"""
    try:
        current_user_id = int(get_jwt_identity())
        
        # 获取查询参数
        page = request.args.get('page', 1, type=int)
        per_page = request.args.get('per_page', 20, type=int)
        date_filter = request.args.get('date')  # 可选：按日期筛选
        
        query = DiaryEntry.query.filter_by(user_id=current_user_id)
        
        # 如果指定了日期，筛选该日期的条目
        if date_filter:
            try:
                filter_date = datetime.strptime(date_filter, '%Y-%m-%d').date()
                query = query.filter(db.func.date(DiaryEntry.created_at) == filter_date)
            except ValueError:
                return jsonify({'error': '日期格式错误，请使用 YYYY-MM-DD 格式'}), 400
        
        # 按创建时间倒序排列
        query = query.order_by(DiaryEntry.created_at.desc())
        
        # 分页
        pagination = query.paginate(
            page=page, 
            per_page=per_page, 
            error_out=False
        )
        
        entries = [entry.to_dict() for entry in pagination.items]
        
        return jsonify({
            'success': True,
            'data': entries,
            'pagination': {
                'page': page,
                'per_page': per_page,
                'total': pagination.total,
                'pages': pagination.pages,
                'has_next': pagination.has_next,
                'has_prev': pagination.has_prev
            }
        }), 200
        
    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500


# ==================== GET - 获取单个日记条目 ====================
@bp.route('/entries/<int:entry_id>', methods=['GET'])
@jwt_required()
def get_diary_entry(entry_id):
    """获取单个日记条目"""
    try:
        current_user_id = int(get_jwt_identity())
        
        entry = DiaryEntry.query.filter_by(
            id=entry_id, 
            user_id=current_user_id
        ).first()
        
        if not entry:
            return jsonify({'error': '日记条目不存在'}), 404
        
        return jsonify({
            'success': True,
            'data': entry.to_dict(),
        }), 200
        
    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500


# ==================== POST - 创建日记条目 ====================
@bp.route('/entries', methods=['POST'])
@jwt_required()
def create_diary_entry():
    """创建新的日记条目"""
    try:
        current_user_id = int(get_jwt_identity())
        data = request.get_json()
        
        # 数据验证
        if not data or not data.get('content'):
            return jsonify({'error': '日记内容不能为空'}), 400
        
        # 处理标签
        tags = data.get('tags', [])
        tags_str = ','.join(tags) if isinstance(tags, list) else tags
        
        # 创建日记条目
        new_entry = DiaryEntry(
            user_id=current_user_id,
            content=data['content'],
            mood=data.get('mood'),
            weather=data.get('weather'),
            tags=tags_str
        )
        
        db.session.add(new_entry)
        db.session.commit()
        
        return jsonify({
            'success': True,
            'data': new_entry.to_dict(),
            'message': '日记创建成功'
        }), 201
        
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500


# ==================== PUT - 更新日记条目 ====================
@bp.route('/entries/<int:entry_id>', methods=['PUT'])
@jwt_required()
def update_diary_entry(entry_id):
    """更新日记条目"""
    try:
        current_user_id = int(get_jwt_identity())
        data = request.get_json()
        
        # 查询并验证权限
        entry = DiaryEntry.query.filter_by(
            id=entry_id,
            user_id=current_user_id
        ).first()
        
        if not entry:
            return jsonify({'error': '日记条目不存在'}), 404
        
        # 更新字段
        if 'content' in data:
            entry.content = data['content']
        if 'mood' in data:
            entry.mood = data['mood']
        if 'weather' in data:
            entry.weather = data['weather']
        if 'tags' in data:
            tags = data['tags']
            entry.tags = ','.join(tags) if isinstance(tags, list) else tags
        
        from models import get_beijing_time
        entry.updated_at = get_beijing_time()
        db.session.commit()
        
        return jsonify({
            'success': True,
            'data': entry.to_dict(),
            'message': '更新成功'
        }), 200
        
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500


# ==================== DELETE - 删除日记条目 ====================
@bp.route('/entries/<int:entry_id>', methods=['DELETE'])
@jwt_required()
def delete_diary_entry(entry_id):
    """删除日记条目"""
    try:
        current_user_id = int(get_jwt_identity())
        
        # 查询并验证权限
        entry = DiaryEntry.query.filter_by(
            id=entry_id,
            user_id=current_user_id
        ).first()
        
        if not entry:
            return jsonify({'error': '日记条目不存在'}), 404
        
        db.session.delete(entry)
        db.session.commit()
        
        return jsonify({
            'success': True,
            'message': '删除成功'
        }), 200
        
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500


# ==================== AI总结相关功能 ====================

def call_ai_api(prompt):
    """调用AI API生成内容"""
    try:
        # 这里可以集成各种AI服务，比如OpenAI、Claude等
        # 示例使用环境变量配置的API
        api_key = os.getenv('AI_API_KEY')
        api_url = os.getenv('AI_API_URL', 'https://api.openai.com/v1/chat/completions')
        
        if not api_key:
            return None, "AI API密钥未配置"
        
        headers = {
            'Authorization': f'Bearer {api_key}',
            'Content-Type': 'application/json'
        }
        
        data = {
            'model': 'gpt-3.5-turbo',
            'messages': [
                {'role': 'user', 'content': prompt}
            ],
            'max_tokens': 1000,
            'temperature': 0.7
        }
        
        response = requests.post(api_url, headers=headers, json=data, timeout=30)
        
        if response.status_code == 200:
            result = response.json()
            return result['choices'][0]['message']['content'], None
        else:
            return None, f"AI API调用失败: {response.status_code}"
            
    except Exception as e:
        return None, f"AI API调用异常: {str(e)}"


@bp.route('/summarize', methods=['POST'])
@jwt_required()
def generate_daily_summary():
    """生成指定日期的AI总结"""
    try:
        current_user_id = int(get_jwt_identity())
        data = request.get_json()
        
        # 获取日期参数，默认为今天
        target_date = data.get('date')
        if target_date:
            try:
                target_date = datetime.strptime(target_date, '%Y-%m-%d').date()
            except ValueError:
                return jsonify({'error': '日期格式错误，请使用 YYYY-MM-DD 格式'}), 400
        else:
            target_date = date.today()
        
        # 检查是否已有该日期的总结
        existing_summary = DiarySummary.query.filter_by(
            user_id=current_user_id,
            date=target_date
        ).first()
        
        if existing_summary:
            return jsonify({
                'success': True,
                'data': existing_summary.to_dict(),
                'message': '该日期已有总结'
            }), 200
        
        # 获取该日期的所有日记条目
        entries = DiaryEntry.query.filter(
            DiaryEntry.user_id == current_user_id,
            db.func.date(DiaryEntry.created_at) == target_date
        ).order_by(DiaryEntry.created_at.asc()).all()
        
        if not entries:
            return jsonify({'error': '该日期没有日记条目'}), 400
        
        # 构建AI提示词
        diary_content = '\n'.join([
            f"{entry.created_at.strftime('%H:%M')} - {entry.content}"
            for entry in entries
        ])
        
        prompt = f"""
请根据以下日记内容，生成一份温馨的每日总结：

日记内容：
{diary_content}

请生成：
1. 一份简洁的每日总结（200-300字）
2. 3-5个今日亮点事件
3. 心情分析（基于日记内容分析情绪变化）

请以JSON格式返回：
{{
    "summary": "每日总结内容",
    "highlights": ["亮点1", "亮点2", "亮点3"],
    "mood_analysis": "心情分析内容"
}}
"""
        
        # 调用AI API
        ai_response, error = call_ai_api(prompt)
        
        if error:
            return jsonify({'error': f'AI总结生成失败: {error}'}), 500
        
        try:
            # 解析AI返回的JSON
            import json
            ai_data = json.loads(ai_response)
            
            # 创建总结记录
            summary = DiarySummary(
                user_id=current_user_id,
                date=target_date,
                summary=ai_data.get('summary', ''),
                highlights=','.join(ai_data.get('highlights', [])),
                mood_analysis=ai_data.get('mood_analysis', '')
            )
            
            db.session.add(summary)
            db.session.commit()
            
            return jsonify({
                'success': True,
                'data': summary.to_dict(),
                'message': 'AI总结生成成功'
            }), 201
            
        except json.JSONDecodeError:
            return jsonify({'error': 'AI返回格式错误'}), 500
        
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500


@bp.route('/summaries', methods=['POST'])
@jwt_required()
def create_diary_summary():
    """创建日记总结（由前端AI生成后提交）"""
    try:
        current_user_id = int(get_jwt_identity())
        data = request.get_json()
        
        # 数据验证
        if not data or not data.get('date'):
            return jsonify({'error': '日期不能为空'}), 400
        
        if not data.get('summary'):
            return jsonify({'error': '总结内容不能为空'}), 400
        
        # 解析日期
        try:
            target_date = datetime.strptime(data['date'], '%Y-%m-%d').date()
        except ValueError:
            return jsonify({'error': '日期格式错误，请使用 YYYY-MM-DD 格式'}), 400
        
        # 检查是否已有该日期的总结
        existing_summary = DiarySummary.query.filter_by(
            user_id=current_user_id,
            date=target_date
        ).first()
        
        if existing_summary:
            return jsonify({'error': '该日期已有总结'}), 400
        
        # 处理亮点事件
        highlights = data.get('highlights', [])
        highlights_str = ','.join(highlights) if isinstance(highlights, list) else highlights
        
        # 创建总结记录
        summary = DiarySummary(
            user_id=current_user_id,
            date=target_date,
            summary=data['summary'],
            highlights=highlights_str,
            mood_analysis=data.get('mood_analysis', '')
        )
        
        db.session.add(summary)
        db.session.commit()
        
        return jsonify({
            'success': True,
            'data': summary.to_dict(),
            'message': '总结创建成功'
        }), 201
        
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500


@bp.route('/summaries', methods=['GET'])
@jwt_required()
def get_diary_summaries():
    """获取用户的AI总结列表"""
    try:
        current_user_id = int(get_jwt_identity())
        
        # 获取查询参数
        page = request.args.get('page', 1, type=int)
        per_page = request.args.get('per_page', 10, type=int)
        date_filter = request.args.get('date')  # 可选：按日期筛选
        
        query = DiarySummary.query.filter_by(user_id=current_user_id)
        
        # 如果指定了日期，筛选该日期的总结
        if date_filter:
            try:
                filter_date = datetime.strptime(date_filter, '%Y-%m-%d').date()
                query = query.filter(DiarySummary.date == filter_date)
            except ValueError:
                return jsonify({'error': '日期格式错误，请使用 YYYY-MM-DD 格式'}), 400
        
        query = query.order_by(DiarySummary.date.desc())
        
        # 分页
        pagination = query.paginate(
            page=page, 
            per_page=per_page, 
            error_out=False
        )
        
        summaries = [summary.to_dict() for summary in pagination.items]
        
        return jsonify({
            'success': True,
            'data': summaries,
            'pagination': {
                'page': page,
                'per_page': per_page,
                'total': pagination.total,
                'pages': pagination.pages,
                'has_next': pagination.has_next,
                'has_prev': pagination.has_prev
            }
        }), 200
        
    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500


@bp.route('/summaries/<int:summary_id>', methods=['GET'])
@jwt_required()
def get_diary_summary(summary_id):
    """获取单个AI总结"""
    try:
        current_user_id = int(get_jwt_identity())
        
        summary = DiarySummary.query.filter_by(
            id=summary_id,
            user_id=current_user_id
        ).first()
        
        if not summary:
            return jsonify({'error': '总结不存在'}), 404
        
        return jsonify({
            'success': True,
            'data': summary.to_dict(),
        }), 200
        
    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500

